package com.hqbzl.c1.unsate;

import lombok.Data;
import lombok.ToString;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class TestUnsafe {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        final Unsafe safe = (Unsafe) theUnsafe.get(null);
        System.out.println("o = " + safe);
        //  获取偏移地址
        final long idOffset = safe.objectFieldOffset(User.class.getDeclaredField("id"));
        final long nameoffset = safe.objectFieldOffset(User.class.getDeclaredField("name"));
        final User u = new User();
        //  赋值
        final boolean r1 = safe.compareAndSwapInt(u, idOffset, 0, 100);
        final boolean r2 = safe.compareAndSwapObject(u, nameoffset, null, "lisi");
        System.out.println("r1 = " + r1);
        System.out.println("r2 = " + r2);
        System.out.println("u = " + u);

    }

    @ToString
    @Data
    static class User {
        volatile private int id;
        volatile private String name;
    }
}
